<template >
  <div>
    <!-- 顶部栏 -->
    <el-header>
      <van-nav-bar
        title="咖啡师-学生端"
        right-text="退出登录"
        left-arrow
        @click-left="goBack"
        @click-right="logout"
      />
    </el-header>
    <!-- 主要容器 -->
    <el-container style="height: max-content">
      <!-- 侧边显示 -->
      <el-aside width="15%" style="height: 100%; background-color: white">
        <div style="font-weight: bold; font-size: large">
          {{ "学生编号：" + studentLoginName }}<br />
          {{ "考位编号：" + station }}<br />
          {{ "开始时间：" }}<br />{{ startTime }}<br />
          {{ "结束时间：" }}<br />{{ endTime }}<br />
        </div>
        <el-button
          class="back-to-top"
          @click="scrollToTop"
          type="info"
          circle
          icon="el-icon-top"
          size="large"
        />
        <br />
        <!-- <el-button class="refresh-btn" @click="refresh"
                     type="primary"
                     circle
                     icon="el-icon-refresh"
                     size="large" /> -->
      </el-aside>
      <!-- 答题操作区 -->
      <el-container>
        <el-main>
          <van-list
            v-model="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
          >
            <!-- <el-row>
                  <el-col v-for="bigQuestions in list[0]" :key="bigQuestions" > -->
            <el-card
              class="bigQues-card"
              v-for="bigQuestions in list"
              :key="bigQuestions.id"
              :title="bigQuestions"
              shadow="never"
            >
              <div slot="header" class="clearfix">
                <span style="font-weight: bold; font-size: x-large">{{ bigQuestions.title }}</span>
              </div>
              <div style="margin-bottom: 3%; white-space: pre-line">
                {{ bigQuestions.content }}
              </div>

              <el-collapse accordion v-if="bigQuestions.more">
                <el-collapse-item>
                  <template slot="title">
                    <span style="font-weight: bold; font-size: medium">{{ "展开小题" }}</span>
                  </template>
                  <br />
                  <el-card
                    v-if="
                      item.type === '填空题' ||
                      item.type === '多填空题' ||
                      item.type === '单选题'
                    "
                    v-for="item in bigQuestions.QA"
                    :key="item.id"
                    :title="item"
                    name="stepper"
                    :label="item.question"
                    label-width="70%"
                  >
                    <div slot="header" class="clearfix">
                      <span style="font-weight: bold"> {{ item.title }}</span>
                    </div>
                    <!-- 未提交状态 -->
                    <div v-if="item.status === 0">
                      <!--多个空的填空题-->
                      <div v-if="item.type === '多填空题'">
                        <span style="color: #5a5e66">{{
                          "题目类型：" + item.type
                        }}</span>
                        <van-field
                          style="
                            font-weight: bold;
                            font-size: small;
                            width: auto;
                            color: #2c3e50;
                          "
                          v-for="qes in item.answer"
                          :key="qes.id"
                          v-model="qes.a"
                          :label="qes.q"
                          placeholder="请输入答案"
                          @input="
                            onHandleMutiSubAns(
                              item.id,
                              item.isAuto,
                              item.answer,
                              paperId
                            )
                          "
                        />
                      </div>
                      <!--一个空的普通填空题-->
                      <div
                        v-if="
                          item.type === '填空题' &&
                          !isObject(item.question) &&
                          !isArray(item.question)
                        "
                      >
                        <span style="color: #5a5e66">{{
                          "题目类型：" + item.type
                        }}</span>
                        <br />
                        <span style="font-weight: bold; width: auto">{{
                          item.question + ": "
                        }}</span>
                        <van-cell-group>
                          <van-field
                            style="
                              font-weight: bold;
                              font-size: small;
                              width: auto;
                              color: #2c3e50;
                            "
                            v-model="item.answer"
                            label="回答："
                            placeholder="请输入答案"
                            @input="
                              onHandleSubAns(
                                item.id,
                                item.isAuto,
                                item.answer,
                                paperId
                              )
                            "
                          />
                        </van-cell-group>
                      </div>
                      <!--单选择题-->
                      <div v-if="item.type === '单选题'">
                        <span style="color: #5a5e66">{{
                          "题目类型：" + item.type
                        }}</span>
                        <br />
                        <span style="font-weight: bold; width: auto">{{
                          item.question[0].title
                        }}</span>
                        <br />
                        <el-select
                          v-model="item.answer"
                          placeholder="请选择"
                          @change="
                            onHandleSubAns(
                              item.id,
                              item.isAuto,
                              item.answer,
                              paperId
                            )
                          "
                        >
                          <el-option
                            v-for="opt in item.question[0].options"
                            :key="Object.values(opt)[0]"
                            :label="Object.values(opt)[0]"
                            :value="Object.values(opt)[0]"
                          >
                          </el-option>
                        </el-select>
                        <!-- <span v-for="opt in item.question[0].options"> {{ Object.values(opt) }}</span> -->
                      </div>
                    </div>
                    <!-- 提交锁定状态 -->
                    <div v-else>
                      <!--多个空的填空题-->
                      <div v-if="item.type === '多填空题'">
                        <span style="color: #5a5e66">{{
                          "题目类型：" + item.type
                        }}</span>
                        <van-field
                          style="
                            font-weight: bold;
                            font-size: small;
                            width: auto;
                            color: #2c3e50;
                          "
                          v-for="qes in item.answer"
                          :key="qes.id"
                          v-model="qes.a"
                          :label="qes.q"
                          placeholder="请输入答案"
                          @input="
                            onHandleMutiSubAns(
                              item.id,
                              item.isAuto,
                              item.answer,
                              paperId
                            )
                          "
                          disabled
                        />
                      </div>
                      <!--一个空的普通填空题-->
                      <div
                        v-if="
                          item.type === '填空题' &&
                          !isObject(item.question) &&
                          !isArray(item.question)
                        "
                      >
                        <span style="color: #5a5e66">{{
                          "题目类型：" + item.type
                        }}</span>
                        <br />
                        <span style="font-weight: bold; width: auto">{{
                          item.question + ": "
                        }}</span>
                        <van-cell-group>
                          <van-field
                            style="
                              font-weight: bold;
                              font-size: small;
                              width: auto;
                              color: #2c3e50;
                            "
                            v-model="item.answer"
                            label="回答："
                            placeholder="请输入答案"
                            @input="
                              onHandleSubAns(
                                item.id,
                                item.isAuto,
                                item.answer,
                                paperId
                              )
                            "
                            disabled
                          />
                        </van-cell-group>
                      </div>
                      <!--单选择题-->
                      <div v-if="item.type === '单选题'">
                        <span style="color: #5a5e66">{{
                          "题目类型：" + item.type
                        }}</span>
                        <br />
                        <span style="font-weight: bold; width: auto">{{
                          item.question[0].title
                        }}</span>
                        <br />
                        <el-select
                          v-model="item.answer"
                          placeholder="请选择"
                          @change="
                            onHandleSubAns(
                              item.id,
                              item.isAuto,
                              item.answer,
                              paperId
                            )
                          "
                          disabled
                        >
                          <el-option
                            v-for="opt in item.question[0].options"
                            :key="Object.values(opt)[0]"
                            :label="Object.values(opt)[0]"
                            :value="Object.values(opt)[0]"
                          >
                          </el-option>
                        </el-select>
                        <!-- <span v-for="opt in item.question[0].options"> {{ Object.values(opt) }}</span> -->
                      </div>
                    </div>
                    <center>
                      <br />
                      <el-button
                        v-if="item.status === 0 && item.type === '多填空题'"
                        @click="
                          onHandleSubStatMutiAns(
                            item.id,
                            item.isAuto,
                            item.answer,
                            paperId
                          )
                        "
                        type="primary"
                        style="width: 80%"
                        >提 交</el-button
                      >
                      <el-button
                        v-else-if="
                          item.status === 0 && item.type !== '多填空题'
                        "
                        @click="
                          onHandleSubStatAns(
                            item.id,
                            item.isAuto,
                            item.answer,
                            paperId
                          )
                        "
                        type="primary"
                        style="width: 80%"
                        >提 交</el-button
                      >
                      <el-button v-else type="info" style="width: 80%"
                        >已 提 交</el-button
                      >
                      <br /><br />
                    </center>
                    <div style="float: right; margin: 10px">
                      <span>{{ "分值：" + item.totalScore }}</span>
                    </div>
                  </el-card>
                  <!-- <el-card v-else>
                      <div slot="header" class="clearfix">
                        <span style="font-weight: bold; ">
                          {{ '操作题' }}</span>
                      </div>
                    </el-card> -->
                  <br />
                </el-collapse-item>
              </el-collapse>
            </el-card>
            <!-- </el-col>
          </el-row> -->
          </van-list>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import {
  getPaper,
  submitAns,
  submitAnsFinal,
} from "@/api/examinee/examinee.js";
import answer from "@/views/coffee/answer/index.vue";
export default {
  name: "Examiner",
  computed: {
    answer() {
      return answer;
    },
  },
  data() {
    return {
      // oldList:
      paperId: null,
      station: null,
      studentLoginName: null,
      startTime: null,
      endTime: null,
      list: [],
      loading: false,
      finished: false,
      refreshing: false,
      t_muti: "", //多空填空题临时变量
      t_answers: {},
      all_muti: [],
    };
  },
  filters: {
    formatTime(value) {
      const date = new Date(value);
      const hours = date.getHours();
      const minutes = date.getMinutes();
      return `${hours}:${minutes < 10 ? "0" + minutes : minutes}`;
    },
  },
  watch: {},
  created() {
    // this.getInfoList()
    this.paperId = this.$route.query.paperId;
    (this.station = this.$route.query.station),
      (this.studentLoginName = this.$route.query.studentLoginName),
      (this.startTime = this.$route.query.startTime),
      (this.endTime = this.$route.query.endTime);
  },
  methods: {
    getInfoList() {
      this.loading = true;
      this.paperId = this.$route.query.paperId;
      let that = this;
      getPaper(this.paperId)
        .then((response) => {
          //处理字符串数组转换成数组对象（填空题中一题多个空）
          const _t_List = response.data.paper;
          for (const bigQues in _t_List) {
            for (const ques in _t_List[bigQues].QA) {
              if (
                _t_List[bigQues].QA[ques].type != "操作题" &&
                _t_List[bigQues].QA[ques].type != "判断题"
              ) {
                _t_List[bigQues].more = true;
              }
              if (_t_List[bigQues].QA[ques].question != null) {
                _t_List[bigQues].QA[ques].question = _t_List[bigQues].QA[
                  ques
                ].question.replace(/\n/g, "");
                _t_List[bigQues].QA[ques].question = _t_List[bigQues].QA[
                  ques
                ].question.replace(/\r/g, "");
                _t_List[bigQues].QA[ques].question = _t_List[bigQues].QA[
                  ques
                ].question.replace(/\t/g, "");

                if (
                  _t_List[bigQues].QA[ques].type == "多填空题" ||
                  _t_List[bigQues].QA[ques].type == "单选题"
                ) {
                  _t_List[bigQues].QA[ques].question = eval(
                    _t_List[bigQues].QA[ques].question
                  );
                }
              }
              if (_t_List[bigQues].QA[ques].answer != null) {
                _t_List[bigQues].QA[ques].answer = _t_List[bigQues].QA[
                  ques
                ].answer.replace(/\n/g, "");
                _t_List[bigQues].QA[ques].answer = _t_List[bigQues].QA[
                  ques
                ].answer.replace(/\r/g, "");
                _t_List[bigQues].QA[ques].answer = _t_List[bigQues].QA[
                  ques
                ].answer.replace(/\t/g, "");
                if (_t_List[bigQues].QA[ques].type == "多填空题") {
                  _t_List[bigQues].QA[ques].answer = eval(
                    _t_List[bigQues].QA[ques].answer
                  );
                }
              }
            }
          }
          // console.log("*t_answers*：",that.t_answers)
          // console.log("_T_LIST:",_t_List)
          this.list = _t_List;
          this.total = response.total;
          this.loading = false;
        })
        .catch((res) => {
          console.log("****ERROR*****", res);
        });
    },

    onLoad() {
      setTimeout(() => {
        if (this.refreshing) {
          this.list = [];
          this.refreshing = false;
        }
        this.getInfoList();
        this.loading = false;
        this.finished = true;

        if (this.list.length >= 40) {
          this.finished = true;
        }
      }, 1000);
    },
    onRefresh() {
      // 清空列表数据
      this.finished = false;
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true;
      this.onLoad();
    },
    //刷新按钮对应方法
    refresh() {
      this.getInfoList();
    },

    findAllMutiObjectsById(id) {
      return this.all_muti.filter((item) => item.id === id);
    },

    //处理多个空格填空小题答案
    onHandleMutiSubAns(qid, isAuto, qAns, paperId) {
      // console.log("qid value:",qid,";isAuto:",isAuto,";Ans:",qAns,)
      submitAns(qid, isAuto, JSON.stringify(qAns), paperId)
        .then((res) => {
          console.log("RES:", res);
          if (res.code != 200) {
            this.$message.error(res);
          }
          this.getInfoList();
        })
        .catch((error) => {
          // 处理错误情况
          this.$message.error(res);
        });
    },
    //提交答案小题答案
    onHandleSubAns(qid, isAuto, qAns, paperId) {
      // console.log("qid value:",qid,";Ans:",qAns,";isAuto:",isAuto)
      submitAns(qid, isAuto, qAns, paperId)
        .then((res) => {
          // console.log("******RES*******",res)
          if (res.code != 200) {
            this.$message.error(res);
          }
        })
        .catch((res) => {
          this.$message.error(res);
        });
    },
    //锁定答题
    onHandleSubStatAns(qid, isAuto, qAns, paperId) {
      this.$modal.confirm('是否确认提交，提交后无法修改回答').then(() => {
        submitAnsFinal(qid, isAuto, qAns, paperId)
          .then((res) => {
            // console.log("******RES*******",res)
            if (res.code != 200) {
              this.$message.error(res);
            }
            this.$modal.msgSuccess("提交成功");
            this.getInfoList();
          })
          .catch((res) => {
            this.$message.error(res);
          });        
      }).catch(() => {});
    },
    //锁定答题（多填空）
    onHandleSubStatMutiAns(qid, isAuto, qAns, paperId) {
      this.$modal.confirm('是否确认提交，提交后无法修改回答').then(() => {
        submitAnsFinal(qid, isAuto, JSON.stringify(qAns), paperId)
          .then((res) => {
            // console.log("******RES*******",res)
            if (res.code != 200) {
              this.$message.error(res);
            }
            this.$modal.msgSuccess("提交成功");
            this.getInfoList();
          })
          .catch((res) => {
            this.$message.error(res);
          });        
      }).catch(() => {});
    },
    goBack() {
      this.$router.back();
    },
    async logout() {
      this.$confirm("确定注销并退出系统吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$store.dispatch("LogOut").then(() => {
            location.href = "/index";
          });
        })
        .catch(() => {});
    },
    //列表排序
    orderList(attr) {
      return function (a, b) {
        return a[attr] - b[attr];
      };
    },
    //判断是否为对象
    isObject(item) {
      return typeof item === "object" && item !== null && !Array.isArray(item);
    },
    //判断是否为数组
    isArray(item) {
      return Array.isArray(item);
    },
    //回到顶部
    handleScroll() {
      // 当页面滚动超过一定距离时，显示回到顶部按钮
      const scrollPosition =
        window.pageYOffset || document.documentElement.scrollTop;
      this.showButton = scrollPosition > 100;
    },
    scrollToTop() {
      // 平滑滚动到页面顶部
      const scrollDuration = 500; // 滚动持续时间（毫秒）
      const scrollStep = -window.scrollY / (scrollDuration / 15);

      const scrollInterval = setInterval(() => {
        if (window.scrollY !== 0) {
          window.scrollBy(0, scrollStep);
        } else {
          clearInterval(scrollInterval);
        }
      }, 15);
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss">
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
.bigQues-card {
  margin: 3%;
}
.back-to-top {
  position: fixed;
  bottom: 20px;
  /* 样式可根据需求自定义 */
}
.refresh-btn {
  position: fixed;
  bottom: 90px;
  /* 样式可根据需求自定义 */
}
.footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
</style>
